package com.li.configserve.utils.es;

import com.alibaba.fastjson.JSON;
import com.li.toolkit.constant.LogConst;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * @Description：
 * @Author：LiDong
 * @Create：2021/1/26
 * @Version：1.0.0
 */
@SuppressWarnings("ALL")
public class EsUtils {


    private static final Logger logger = LoggerFactory.getLogger(EsUtils.class);


    /**
     * 判断索引是否存在
     *
     * @param client
     * @param indexName
     * @return
     */
    public static boolean isExistsIndex(RestHighLevelClient client, String indexName) {
        GetIndexRequest indexRequest = new GetIndexRequest(indexName);
        try {
            return client.indices().exists(indexRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            logger.error("=====> isExistsIndex()出错：{}" , e.getMessage());
        }
        return false;
    }

    /**
     * 创建索引
     *
     * @param client
     * @param indexName
     */
    public static void createIndex(RestHighLevelClient client, String indexName) {
        //创建索引请求
        CreateIndexRequest index = new CreateIndexRequest(indexName);
        try {
            //执行请求，获得响应
            CreateIndexResponse response = client.indices().create(index, RequestOptions.DEFAULT);
            logger.info("=====> es创建索引：" + indexName + response);
        } catch (Exception e) {
            logger.error("=====> createIndex()出错：" + e.getMessage());
        }
    }

    public static void deleteIndex(RestHighLevelClient client, String indexName) {
        DeleteIndexRequest index = new DeleteIndexRequest(indexName);
        try {
            //执行请求，获得响应
            AcknowledgedResponse delete = client.indices().delete(index, RequestOptions.DEFAULT);
            logger.info("=====> es删除索引：" + indexName + delete);
        } catch (Exception e) {
            logger.error("=====> deleteIndex()出错：" + e.getMessage());
        }
    }

    /**
     * 添加文档
     *
     * @param client
     * @param indexName
     * @param object
     */
    public static void addDocument(RestHighLevelClient client, String indexName, Object object) {
        //创建索引请求
        IndexRequest request = new IndexRequest(indexName);
        // 数据转换成json 放入请求
        request.source(JSON.toJSONString(object), XContentType.JSON);
        //将请求发出去,获取响应结果
        IndexResponse indexResponse = null;
        try {
            indexResponse = client.index(request, RequestOptions.DEFAULT);
            logger.info("=====> addDocument()：" + JSON.toJSONString(indexResponse));
        } catch (IOException e) {
            logger.error("=====> addDocument()出错：" + e.getMessage());
        }
    }

    /**
     * 根据indexName和indeId判断文档是否存在
     *
     * @param client
     * @param indexName
     * @param indexId
     * @return
     */
    public static boolean isExistsDocument(RestHighLevelClient client, String indexName, String indexId) {
        GetRequest getRequest = new GetRequest(indexName, indexId);
        // 不获取返回的_source 的上下文，会提高速度
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");
        try {
            return client.exists(getRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            logger.error("=====> isExistsDocument()出错：" + e.getMessage());
        }
        return false;
    }

    /**
     * 根据索引名和索引id查询文档
     *
     * @param client
     * @param indexName
     * @param indexId
     * @return
     */
    public static Object getDocument(RestHighLevelClient client, String indexName, String indexId) {
        GetRequest getRequest = new GetRequest(indexName, indexId);
        try {
            return client.get(getRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            logger.error("=====> getDocument()出错：" + e.getMessage());
        }
        return null;
    }


    /**
     * 根据索引名和索引id更新文档
     *
     * @param client
     * @param indexName
     * @param indexId
     * @param object
     */
    public static void updateDocument(RestHighLevelClient client, String indexName, String indexId, Object object) {
        UpdateRequest request = new UpdateRequest(indexName, indexId);
        request.timeout("1s");
        request.doc(JSON.toJSONString(object), XContentType.JSON);
        try {
            UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
            logger.info("=====> updateDocument()：" + JSON.toJSONString(response));
        } catch (IOException e) {
            logger.error("=====> updateDocument()出错：" + e.getMessage());
        }

    }

    /**
     * 根据索引名和索引id删除文档
     *
     * @param client
     * @param indexName
     * @param indexId
     */
    public static void deleteDocument(RestHighLevelClient client, String indexName, String indexId) {
        DeleteRequest request = new DeleteRequest(indexName, indexId);
        request.timeout("1s");
        try {
            DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
            logger.info("=====> deleteDocument()：{}", JSON.toJSONString(response));
        } catch (IOException e) {
            logger.error("=====> deleteDocument()出错：{}", e.getMessage());
        }

    }

    /**
     * 批量新增
     *
     * @param client
     * @param indexName
     * @param list
     */
    public static void multiAdd(RestHighLevelClient client, String indexName, List<Object> list) {
        BulkRequest request = new BulkRequest();
        request.timeout("10s");
        //批量请求，批量更新，删除都差不多！！！不设置id就会自动生成随机id，演示为批量插入
        for (int i = 0; i < list.size(); i++) {
            request.add(new IndexRequest(indexName)
                    .id("" + (i + 1))
                    .source(JSON.toJSONString(list.get(i)), XContentType.JSON));
        }
        try {
            BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
            logger.info("=====> multiAdd()：" + JSON.toJSONString(response));
        } catch (IOException e) {
            logger.error("=====> multiAdd()出错：" + e.getMessage());
        }

    }

    /**
     * 封装Post查询Es中的结果
     */
    public String getEsResultBysql(String sql) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            // 请求的Url
            String urlLocation = "http://127.0.0.1:9200/_sql";
            // 请求体
            String content = "{\"query\":\"" + sql + "\"}";
            URL realUrl = new URL(urlLocation);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            ((HttpURLConnection) conn).setRequestMethod("POST");
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(content);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            logger.info("发送 POST 请求出现异常！{}", e.getMessage());
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                logger.error(LogConst.LOG_FAILURE_PREFIX, ex.getMessage());
            }
        }
        return String.valueOf(result);
    }


}
